package com.hejjon.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hejjon.bean.FileStoreInfo;
import com.hejjon.entity.FileModel;
import com.hejjon.mapper.FileManageMapper;
import com.hejjon.service.IFileManageService;
import com.hejjon.utils.DateUtil;
import com.hejjon.utils.FileUtil;
import com.hejjon.utils.MinIOUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;

@Service
public class FileManageServiceImpl extends ServiceImpl<FileManageMapper, FileModel> implements IFileManageService {


    @Value("${file-upload-base-path}")
    private String fileUploadBasePath;

    @Resource
    private MinIOUtil minioUtil;


    @Override
    public FileStoreInfo uploadFile(MultipartFile file) {
        String dirPath = FileUtil.mkDirByTimestamp(fileUploadBasePath);
        String filename = file.getOriginalFilename();

        try {
            String fileFullPath = FileUtil.createFile(file.getBytes(), filename, dirPath);
            FileStoreInfo fileStoreInfo = minioUtil.uploadFile(file);

            FileModel fileModel = new FileModel();
            fileModel.setId(DateUtil.getUUID());
            fileModel.setFileName(filename);
            fileModel.setFileSize(FileUtil.getFileSize2KB(file));
            fileModel.setUploadTime(LocalDateTime.now());
            fileModel.setUploadDir(dirPath);
            fileModel.setFullPath(fileFullPath);
            fileModel.setDownloadCount(0);
            fileModel.setPreviewUrl(fileStoreInfo.getUrl());
            save(fileModel);

            return fileStoreInfo;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void download(HttpServletResponse response, String fileId) {

        FileModel fileModel = getById(fileId);
        if (fileModel == null) {
            return;
        }

        String fullPath = fileModel.getFullPath();
        String fileName = fileModel.getFileName();
        File file = new File(fullPath);

        try {
            FileUtil.download(response, fileName, file);

            // 更新下载次数
            Integer downloadCount = fileModel.getDownloadCount();
            downloadCount++;

            fileModel.setDownloadCount(downloadCount);
            updateById(fileModel);


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
